package com.wl156.activities;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.xmlpull.v1.XmlPullParserException;

import com.wl156.MyApp;
import com.wl156.lite.R;
import com.wl156.activities.MyCollectCar.GetMyStoreGroupTask;
import com.wl156.model.Certificate;
import com.wl156.model.WebServiceClient;
import com.wl156.utils.Utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MyCollectGroupManage extends Activity implements OnClickListener {

	ListView mList;
	Button mAdd;
	List<String> ids;
	List<String> names;
	List<String> counts;
	protected WebServiceClient mWebServiceClient;
	protected Certificate mCertificate;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.act_my_collect_group_manage);

		mWebServiceClient = new WebServiceClient(this);
		mCertificate = ((MyApp) getApplication()).getCertificateFromXml();

		mList = (ListView) findViewById(R.id.list);
		mAdd = (Button) findViewById(R.id.add);
		mAdd.setOnClickListener(this);

		new GetMyStoreGroupTask().execute();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.add:
			View content = LayoutInflater.from(this).inflate(
					R.layout.dlg_new_collect_group, null);
			final EditText nameEdit = (EditText) content
					.findViewById(R.id.group_name);
			TextView title = (TextView) content.findViewById(R.id.title);
			title.setText("收藏分组名称:");
			AlertDialog.Builder builer = new Builder(this);
			builer.setView(content);
			builer.setNegativeButton("取消", null);
			builer.setPositiveButton("确定",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							final String name = nameEdit.getText().toString();
							if (TextUtils.isEmpty(name)) {
								Toast.makeText(MyCollectGroupManage.this,
										"请填写分组名称", Toast.LENGTH_LONG).show();
							} else {
								new AddStoreGroupTask(name).execute();
							}
						}
					});
			builer.show();
			break;
		}
	}

	class AddStoreGroupTask extends AsyncTask<Void, Void, Object> {
		ProgressDialog mDialog;
		String name;

		public AddStoreGroupTask(String name) {
			this.name = name;
		}

		@Override
		protected void onPreExecute() {
			mDialog = ProgressDialog.show(MyCollectGroupManage.this, "", "添加中");
		};

		@Override
		protected void onPostExecute(Object result) {
			mDialog.dismiss();

			if (result instanceof SoapPrimitive) {
				SoapPrimitive message = (SoapPrimitive) result;
				Toast.makeText(MyCollectGroupManage.this, message.toString(),
						Toast.LENGTH_LONG).show();
			} else if (result instanceof SoapObject) {
				Toast.makeText(MyCollectGroupManage.this, "添加成功",
						Toast.LENGTH_LONG).show();

				new GetMyStoreGroupTask().execute();
			} else {
				Toast.makeText(MyCollectGroupManage.this, "联网失败，请稍候再试",
						Toast.LENGTH_LONG).show();
			}
		};

		@Override
		protected Object doInBackground(Void... params) {
			try {
				return mWebServiceClient.commonModifyStoreGroupAdd(
						mCertificate, name);
			} catch (IOException e) {
				return e;
			} catch (XmlPullParserException e) {
				return e;
			}
		}
	}

	CategoryAdapter adapter;

	public class GetMyStoreGroupTask extends AsyncTask<Void, Void, Object> {
		ProgressDialog mDialog;

		@Override
		protected void onPreExecute() {
			mDialog = ProgressDialog.show(MyCollectGroupManage.this, "", "加载中");
		};

		@Override
		protected void onPostExecute(Object result) {
			try {
				if (result instanceof SoapObject) {
					SoapObject so = (SoapObject) result;
					ids = new ArrayList<String>();
					names = new ArrayList<String>();
					counts = new ArrayList<String>();
					for (int i = 0; i < so.getPropertyCount(); i++) {
						SoapObject line = (SoapObject) so.getProperty(i);
						String id = line.getPropertyAsString(0);
						ids.add(id);
						String name = line.getPropertyAsString(1);
						names.add(name);
						String count = line.getPropertyAsString(2);
						counts.add(count);
					}
					adapter = new CategoryAdapter(ids, names);
					mList.setAdapter(adapter);
				} else {
					Utils.showRetryNetworkDialog(MyCollectGroupManage.this,
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									new GetMyStoreGroupTask().execute();
								}
							});
				}
			} catch (Exception e) {
			}
			mDialog.dismiss();
		};

		@Override
		protected Object doInBackground(Void... params) {
			try {
				return mWebServiceClient.commonGetMyStoreGroups(mCertificate);
			} catch (IOException e) {
				return e;
			} catch (XmlPullParserException e) {
				return e;
			}
		}
	}

	private class CategoryAdapter extends BaseAdapter implements
			OnClickListener {
		List<String> ids;
		List<String> names;

		public CategoryAdapter(List<String> ids, List<String> names) {
			this.ids = ids;
			this.names = names;
		}

		@Override
		public int getCount() {
			return ids.size();
		}

		@Override
		public String getItem(int position) {
			return names.get(position);
		}

		@Override
		public long getItemId(int position) {
			return Long.valueOf(ids.get(position));
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = LayoutInflater.from(MyCollectGroupManage.this).inflate(
					R.layout.item_collect_group, null);
			TextView name = (TextView) v.findViewById(R.id.name);
			name.setText(names.get(position));
			TextView remove = (TextView) v.findViewById(R.id.remove);
			remove.setTag(position);
			remove.setOnClickListener(this);
			TextView add = (TextView) v.findViewById(R.id.update);
			add.setTag(position);
			add.setOnClickListener(this);
			return v;
		}

		class RemoveGroupTask extends AsyncTask<Void, Void, Object> {
			ProgressDialog mDialog;
			View v;

			public RemoveGroupTask(View v) {
				this.v = v;
			}

			@Override
			protected void onPreExecute() {
				mDialog = ProgressDialog.show(MyCollectGroupManage.this, "",
						"删除中");
			};

			@Override
			protected void onPostExecute(Object result) {
				mDialog.dismiss();

				if (result instanceof SoapPrimitive) {
					SoapPrimitive message = (SoapPrimitive) result;
					Toast.makeText(MyCollectGroupManage.this,
							message.toString(), Toast.LENGTH_LONG).show();
				} else if (result instanceof SoapObject) {
					Toast.makeText(MyCollectGroupManage.this, "删除成功",
							Toast.LENGTH_LONG).show();

					int position = (Integer) v.getTag();
					ids.remove(position);
					names.remove(position);
					counts.remove(position);
					adapter.notifyDataSetChanged();
				} else {
					Toast.makeText(MyCollectGroupManage.this, "联网失败，请稍候再试",
							Toast.LENGTH_LONG).show();
				}
			};

			@Override
			protected Object doInBackground(Void... params) {
				try {
					return mWebServiceClient.commonModifyStoreGroupDelete(
							mCertificate, ids.get((Integer) v.getTag()));
				} catch (IOException e) {
					return e;
				} catch (XmlPullParserException e) {
					return e;
				}
			}
		}

		class UpdateGroupTask extends AsyncTask<Void, Void, Object> {
			ProgressDialog mDialog;
			View v;
			String name;

			public UpdateGroupTask(View v, String name) {
				this.v = v;
				this.name = name;
			}

			@Override
			protected void onPreExecute() {
				mDialog = ProgressDialog.show(MyCollectGroupManage.this, "",
						"更改中");
			};

			@Override
			protected void onPostExecute(Object result) {
				mDialog.dismiss();

				if (result instanceof SoapPrimitive) {
					SoapPrimitive message = (SoapPrimitive) result;
					Toast.makeText(MyCollectGroupManage.this,
							message.toString(), Toast.LENGTH_LONG).show();
				} else if (result instanceof SoapObject) {
					Toast.makeText(MyCollectGroupManage.this, "更改成功",
							Toast.LENGTH_LONG).show();

					int position = (Integer) v.getTag();
					names.set(position, name);
					adapter.notifyDataSetChanged();
				} else {
					Toast.makeText(MyCollectGroupManage.this, "联网失败，请稍候再试",
							Toast.LENGTH_LONG).show();
				}
			};

			@Override
			protected Object doInBackground(Void... params) {
				try {
					String oldName = "";
					return mWebServiceClient.commonModifyStoreGroupUpdate(
							mCertificate, ids.get((Integer) v.getTag()),
							oldName, name);
				} catch (IOException e) {
					return e;
				} catch (XmlPullParserException e) {
					return e;
				}
			}
		}

		@Override
		public void onClick(final View v) {
			switch (v.getId()) {
			case R.id.remove: {
				new RemoveGroupTask(v).execute();
			}
				break;
			case R.id.update: {
				View content = LayoutInflater.from(MyCollectGroupManage.this)
						.inflate(R.layout.dlg_new_collect_group, null);
				final EditText nameEdit = (EditText) content
						.findViewById(R.id.group_name);
				TextView title = (TextView) content.findViewById(R.id.title);
				title.setText("新收藏分组名称:");
				AlertDialog.Builder builer = new Builder(
						MyCollectGroupManage.this);
				builer.setView(content);
				builer.setNegativeButton("取消", null);
				builer.setPositiveButton("确定",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								final String name = nameEdit.getText()
										.toString();
								if (TextUtils.isEmpty(name)) {
									Toast.makeText(MyCollectGroupManage.this,
											"请填写分组名称", Toast.LENGTH_LONG)
											.show();
								} else {
									new UpdateGroupTask(v, name).execute();
								}
							}
						});
				builer.show();
			}
				break;
			}
		}
	}
}
